﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Net;

namespace Financial
{
    class ConnectionThread
    {
        private static int connections_ = 0;
        private int qtBytes;
        private byte[] buffer = new byte[1024];
        private ArrayList pacote = new ArrayList();
        private IEnumerator lista;

        //dialer
        private Socket dialer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private IPEndPoint ie = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6000);
        //dialer

        private DLGeneric.DLContabilidade bdL = new DLGeneric.DLContabilidade();
        private DLGeneric.DLContabilidade bdF = new DLGeneric.DLContabilidade();
        public bool sessaoFechada = false;
        public Socket threadClient;
        public int connections
        {
            get
            {
                return connections_;
            }
        }

        public ConnectionThread()
        {
        }

        /// <summary>
        /// Metodo resposável por gerir as ligações com os clientes
        /// </summary>
        public void HandleConnection()
        {
            string id = "";
            Console.WriteLine("Servidor ligado: {0} conectado, ligação nr: {1}", threadClient.RemoteEndPoint.ToString(), ++connections_);
            try
            {
                while (true)
                {
                    qtBytes = threadClient.Receive(buffer); //Indication
                    lista = abrePacote(buffer);
                    lista.MoveNext();
                    string dataStr = lista.Current.ToString();
                    string erro = "";
                    switch (dataStr)
                    {
                        case "VSALDO.REQ":
                            Console.WriteLine(dataStr);
                            lista.MoveNext();
                            id = lista.Current.ToString();
                            pacote.Clear();
                            pacote.Add("VSALDO.RES");
                            pacote.Add(bdL.verSaldo(int.Parse(id)));
                            Console.WriteLine("VSALDO.RES");
                            threadClient.Send(criaPacote(pacote)); //REsponse
                            break;
                        case "ADEPOSSC.REQ":
                            Console.WriteLine(dataStr);
                            lista.MoveNext();
                            id = lista.Current.ToString();
                            lista.MoveNext();
                            pacote.Clear();
                            pacote.Add("ADEPOSSC.RES");
                            pacote.Add(bdL.depositar(int.Parse(id), double.Parse(lista.Current.ToString())));
                            Console.WriteLine("ADEPOSSC.RES");
                            threadClient.Send(criaPacote(pacote));//REsponse
                            break;
                        case "LICITAR.REQ":
                            Console.WriteLine(dataStr);
                            lista.MoveNext();
                            id = lista.Current.ToString();
                            lista.MoveNext();
                            double valor = double.Parse(lista.Current.ToString());
                            lista.MoveNext();
                            pacote.Clear();
                            pacote.Add("LICITAR.RES");
                            pacote.Add(bdF.licitar(int.Parse(id), int.Parse(lista.Current.ToString()), valor));
                            Console.WriteLine("LICITAR.RES");
                            threadClient.Send(criaPacote(pacote));//REsponse
                            break;
                    }
                    if (dataStr == "exit" || erro == "1")
                    {
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Erro nas ligações" + e.ToString());
            }
        }

        /// <summary>
        /// Arraylist->Stream->Serialize->byte[]
        /// </summary>
        /// <param name="pacote"></param>
        /// <returns>Byte[] para ser enviado pelo socket</returns>
        public byte[] criaPacote(ArrayList pacote)
        {
            MemoryStream fs = new MemoryStream();

            fs.Position = 0;
            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(fs, pacote);

            byte[] bufer = fs.ToArray();
            fs.Flush();
            return bufer;
        }

        /// <summary>
        /// byte[]->stream->deserialize->arraylist->enumerator
        /// </summary>
        /// <param name="bufer"></param>
        /// <returns>Devolve o enumerator do pacote recebido</returns>
        public IEnumerator abrePacote(Byte[] bufer)
        {
            MemoryStream ms = new MemoryStream(bufer);
            ms.Position = 0;
            BinaryFormatter formatter = new BinaryFormatter();

            ArrayList pacote = (ArrayList)formatter.Deserialize(ms);
            ms.Flush();
            return pacote.GetEnumerator();
        }
    }
}

